using OpenAI.Builders;
using OpenAI.ObjectModels.RequestModels;
using OpenAI.ObjectModels.SharedModels;

namespace MultiAgentsShared;

public class ToolsRelatedJsonUtils
{
    private class SerializableToolDef
    {
        public string funcName;
        public string funcDescription;
        public PropertyDefinition propertyDefinition;
    }

    public static string SerializeToolDefs(List<ToolDefinition> toolDefinitions)
    {
        var serializableToolDefs = new List<SerializableToolDef>();
        foreach (var toolDef in toolDefinitions)
        {
            serializableToolDefs.Add(new SerializableToolDef
            {
                funcName = toolDef.Function.Name,
                funcDescription = toolDef.Function.Description,
                propertyDefinition = toolDef.Function.Parameters
            });
        }
        return SerializableObjectBase.ConvertToJson(serializableToolDefs);
    }

    public static List<ToolDefinition> DeserializeToolDefs(string json)
    {
        var serializableToolDefs = SerializableObjectBase.FromJson<List<SerializableToolDef>>(json);
        var toolDefsOut = new List<ToolDefinition>();
        foreach (var toolDefIn in serializableToolDefs)
        {
            var builder = new FunctionDefinitionBuilder(toolDefIn.funcName, toolDefIn.funcDescription);

            var toolDefinition = ToolDefinition.DefineFunction(builder.Validate().Build());
            toolDefinition.Function.Parameters = toolDefIn.propertyDefinition;
            toolDefsOut.Add(toolDefinition);

        }
        return toolDefsOut;
    }
}
